package org.grenobus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.grenobus.html.SimpleHTML;

public class BusSchedule {

	class Minute {
		int minute;
		int note;
		
		public Minute (int minute, int note) {
			this.minute = minute;
			this.note = note;
		}
	}
	
	class PerHourSchedule {
		int hour;
		List<Minute> minutes = new ArrayList<Minute>(10);	
		
		public PerHourSchedule(String hour) {
			this.hour = Integer.parseInt(hour);
		}
		public PerHourSchedule(int hour) {
			this.hour = hour;
		}
	}
	
	List<PerHourSchedule> mSchedule = new ArrayList<PerHourSchedule>(20); 
	String mDirection;

	static private SimpleHTML getChild(SimpleHTML parent, String tag, int pos) {
		List<SimpleHTML> children = parent.getChildren();
		
		if (children == null) return null;
		
		for (SimpleHTML html: children) {
			if (!tag.equals(html.getTag())) continue;
			
			if (pos == 0) return html;
			--pos;
		}
		
		return null;
	}
	
	static private SimpleHTML followPath(SimpleHTML root, String path[]) {
		SimpleHTML res = root;
		
		for (String elem: path) {
			res = getChild(res, elem.substring(1), elem.charAt(0));
			if (res == null) return null;
		}
		
		return res;
	}
	
	public BusSchedule(SimpleHTML html) {
		SimpleHTML table = followPath(html, new String[] { "\0html", "\0head", "\0body", "\0table"});
		
		if (table == null) return;
		
		SimpleHTML dir = followPath(table, new String[] { "\1td" });
		SimpleHTML schedule = followPath(table, new String[] { "\2table", "\0table", "\0table"});
		
		if (schedule == null) return;
		
		mDirection = dir.getChildren().get(0).getText();
		Iterator<PerHourSchedule> it = null;
		
		for (SimpleHTML h: schedule.getChildren()) {
			if ("td".equals(h.getTag())) {
				mSchedule.add(new PerHourSchedule(h.getChildren().get(0).getText()));
			} else {
				if (it == null) it = mSchedule.iterator();
				
				PerHourSchedule hour = it.next();
				for (SimpleHTML h2: h.getChildren()) {
					int minute = Integer.parseInt(h2.getChildren().get(0).getText());
					int note = 0;
					if (h2.getChildren().size() > 1) note = Integer.parseInt(h2.getChildren().get(1).getText());
					hour.minutes.add(new Minute(minute, note));
				}
			}
		}
		
		mDirection.toString();
	}
	
	public List<PerHourSchedule> getSchedule() {
		return mSchedule;
	}
	
	public String getDirection() {
		return mDirection;
	}

	// For Parcel
	public int describeContents() {
		return 0;
	}
}
